package net.lb.socketserver.interceptor.impl.auth.des;

import javax.annotation.Resource;
import net.lb.baseutil.collection.ByteCache;
import net.lb.baseutil.encrypt.DesUtil;
import net.lb.baseutil.encrypt.EnDecrpt;
import net.lb.socketserver.bus.ServerChannelInfo;
import net.lb.socketserver.bus.Message;
import net.lb.socketserver.interceptor.MessageInterceptor;

@Resource
public class DESEncryptIntercepror implements MessageInterceptor
{
    @Override
    public int getOrder()
    {
        return 0;
    }
    
    @Override
    public int inInterceptor(Message message)
    {
        ServerChannelInfo channelInfo = message.getChannelInfo();
        if (channelInfo.getEndecrpt() == null)
        {
            DesUtil desUtil = new DesUtil();
            desUtil.setKey(channelInfo.getKey());
            channelInfo.setEndecrpt(desUtil);
        }
        EnDecrpt enDecrpt = channelInfo.getEndecrpt();
        ByteCache businessData = message.getBusinessData();
        byte[] result = enDecrpt.decrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return MessageInterceptor.next;
    }
    
    @Override
    public int outInterceptor(Message message)
    {
        ServerChannelInfo channelInfo = message.getChannelInfo();
        ByteCache businessData = message.getBusinessData();
        EnDecrpt enDecrpt = channelInfo.getEndecrpt();
        byte[] result = enDecrpt.encrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return MessageInterceptor.next;
    }
}
